package com.atguigu.gulimall.search.thread;

import java.util.concurrent.*;

public class ThreadTest {

    //当前系统线程池只有一两个，每个异步任务，提交给线程池让他自己去执行
  public static   ExecutorService executorService = Executors.newFixedThreadPool(10);

    public  static ThreadPoolExecutor executor = new ThreadPoolExecutor(5,
            200,
            10,
            TimeUnit.SECONDS,
            new LinkedBlockingDeque<>(100000),
            Executors.defaultThreadFactory(),
            new ThreadPoolExecutor.AbortPolicy());
    //Executors.newCachedThreadPool()   core是0,所有都可以回收
    //Executors.newFixedThreadPool()   固定大小,core=max;都不可以回收
    //Executors.newScheduledThreadPool()   定时任务得线程池
    //Executors.newSingleThreadExecutor() 单线程得线程池，后台从队列里面获取任务，挨个执行。

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        System.out.println("main....start");
//           CompletableFuture.runAsync(()->{
//               System.out.println("当前线程：" + Thread.currentThread().getId());
//               int i = 10 / 2;
//               System.out.println("运行结果：" + i);
//
//           },executor);
//        CompletableFuture<Integer> integerCompletableFuture = CompletableFuture.supplyAsync(() -> {
//            System.out.println("当前线程：" + Thread.currentThread().getId());
//            int i = 10 / 0;
//            System.out.println("运行结果：" + i);
//            return i;
//        }, executor).whenComplete((res,excption)->{
//            //虽然能得到异常信息，但是没法修改返回数据
//            System.out.println("运行成功结果： "+res+"运行失败异常： "+excption);
//        }).exceptionally(throwable->{
//            //可以感知异常，同时返回默认值
//            System.out.println(throwable);
//            return 10;
//        });
//        Integer integer = integerCompletableFuture.get();
//        System.out.println("main....end      "+integer);

//        CompletableFuture<Integer> integerCompletableFuture = CompletableFuture.supplyAsync(() -> {
//            System.out.println("当前线程：" + Thread.currentThread().getId());
//            int i = 10 / 2;
//            System.out.println("运行结果：" + i);
//            return i;
//        }, executor).handle((res, excption) -> {
//            if (res != null) {
//                return res * 2;
//            }
//            if (excption != null) {
//                return 0;
//            }
//            return 0;
//        }).thenApply((item) -> {
//            System.out.println("线程二启动:  " + item * 5);
//            return item * 5;
//        }).thenApply(item -> {
//            System.out.println("线程三启动： " + item);
//            return item;
//        });
//        System.out.println("main....end  "+integerCompletableFuture.get());

        CompletableFuture<String> future01 = CompletableFuture.supplyAsync(() -> {
                        try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("线程1：" + Thread.currentThread().getId());
            return "我是中国人";
        }, executor);

        CompletableFuture<String> future02 = CompletableFuture.supplyAsync(() -> {
//            try {
//                Thread.sleep(1000);
//            } catch (InterruptedException e) {
//                e.printStackTrace();
//            }
            System.out.println("线程2：" + Thread.currentThread().getId());
            return "我爱中国人";
        }, executor);

        CompletableFuture<Object> objectCompletableFuture = CompletableFuture.anyOf(future01, future02);
//        CompletableFuture<String> voidCompletableFuture = future01.applyToEitherAsync(future02, (f1) -> {
//            System.out.println("线程3： " + Thread.currentThread().getId() + "参数： " + f1);
//            return f1;
//        }, executor);

//        CompletableFuture<Void> voidCompletableFuture = future01.runAfterEitherAsync(future02, () -> {
//            System.out.println("线程3： "+Thread.currentThread().getId());
//        }, executor);
//        CompletableFuture<String> future = future01.thenCombineAsync(future02, (f1, f2) -> {
//            return "线程1： " + f1 + "  " + "线程2： " + f2;
//        }, executor);
//        CompletableFuture<Void> voidCompletableFuture = future01.thenAcceptBothAsync(future02, (f1, f2) -> {
//            System.out.println("线程三" + Thread.currentThread().getId() + "f1得值： " + f1 + "f2得值： " + f2);
//        }, executor);

//        future01.runAfterBothAsync(future02,()->{
//            System.out.println("线程三"+Thread.currentThread().getId());
//        },executor);

        System.out.println("main.....end"+objectCompletableFuture.get());
    }

    public static void thread(String[] args) throws ExecutionException, InterruptedException {
//        System.out.println("main....start");
//        Thread01 thread01 = new Thread01();
//        thread01.start();      //启动线程
//        System.out.println("main....end");
//        System.out.println("main....start");
//        Runnable01 runnable01 = new Runnable01();
//        new Thread(runnable01).start();
//        System.out.println("main....end");


        System.out.println("main....start");
//        FutureTask<Integer> integerFutureTask = new FutureTask<>(new Callable01());
//        new Thread(integerFutureTask).start();
//        //等待线程全部执行完成，获取返回结果
//        Integer integer = integerFutureTask.get();
        executorService.execute(new Thread01());

        System.out.println("main....end");

        /**
         * 七大参数
         *    public ThreadPoolExecutor(int corePoolSize,
         *                               int maximumPoolSize,
         *                               long keepAliveTime,
         *                               TimeUnit unit,
         *                               BlockingQueue<Runnable> workQueue,
         *                               ThreadFactory threadFactory,
         *                               RejectedExecutionHandler handler) {
         *  corePoolSize:[5] 核心线程数[一直存在除非@code allowCoreThreadTimeOut]； 线程池，创建好以后就准备就绪
         *  可以理解为 Thread thread=new Thread(); thread.start();
         *  maximumPoolSize:[200] 最大线程数;控制资源
         *  keepAliveTime:存活时间，如果当前的线程数量大于core的数量
         *    释放空闲的线程（maximumPoolSize - corePoolSize） 只要线程空闲大于指定的keepAliveTime；
         *    unit:时间单位
         *    blockingQueue<Runnable> workQueue:阻塞队列。如果任务有很多，就会将目前多的任务放在队列里面
         *    ，只要线程空闲。就会去队列里面取出新的任务执行。
         *    threadFactory:线程的创建工厂
         *    RejectedExecutionHandler handler 如果队列满了，按照我们指定的拒绝策略执行任务
         *
         *    工作顺序：
         *    1） 线程池创建，准备好core数量的核心线程，准备接受任务
         *    1.1 core满了，就直接开新线程执行，最大只能开到max指定的数量
         *    1.2 阻塞队列满了，就直接开新线程执行，最大只能开到max指定的数量
         *    1.3 max满了就用RejectedExecutionHandler 拒绝任务
         *    1.4 max都执行完成，很多空闲，在指定的时间keepAliveTime以后，释放max-core这些线程
         *            new LinkedVlockingDeque<>():默认是Integer的最大值。内存不够
         *
         *    一个线程 core 7; max 20 , queue: 50 ,100并发进来怎么分配的；
         *    7个会立即得到执行，50个会进入队列，在开13个进行执行.剩下得30个就使用拒绝策略。
         *    * */



    }


    public static class Thread01 extends Thread {
        @Override
        public void run() {
            System.out.println("当前线程：" + Thread.currentThread().getId());
            int i = 10 / 2;
            System.out.println("运行结果：" + i);


        }
    }

    public static class Runnable01 implements Runnable{

        @Override
        public void run() {
            System.out.println("当前线程：" + Thread.currentThread().getId());
            int i = 10 / 2;
            System.out.println("运行结果：" + i);
        }
    }

    public static class Callable01 implements Callable<Integer>{

        @Override
        public Integer call() throws Exception {
            System.out.println("当前线程：" + Thread.currentThread().getId());
            int i = 10 / 2;
            System.out.println("运行结果：" + i);
            return i;
        }
    }

}
